﻿using BLL;
using IBLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tools;
using webMvc.Models.Jurisdiction;

namespace webMvc.Authorization
{
	public class LoginAuthentication : AuthorizeAttribute
	{
		IUserInfoService userInfosService = new UserInfoService();
		protected override bool AuthorizeCore(HttpContextBase httpContext)
		{
			var SessionIsOk = true;
			string Token = "";
			if (httpContext.Session["token"] != null)
			{
				ServiceUserToken serviceUserToken = httpContext.Session["token"] as ServiceUserToken;
				if (serviceUserToken != null)
				{
					Token = serviceUserToken.Token;
					SessionIsOk = false;
				}
			}
			//从请求的token进行验证,或者从cookie中进行验证
			else if (httpContext.Request["token"] != null)
			{
				string ClientToken = httpContext.Request["token"].ToString();
				SessionIsOk = !getTokenIsOk(Token, ClientToken, httpContext);
			}
			else if (httpContext.Request.Cookies["token"] != null)
			{
				string ClientToken = httpContext.Request.Cookies["token"].ToString();
				SessionIsOk = !getTokenIsOk(Token, ClientToken, httpContext);
			}

			return SessionIsOk;
		}

		protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
		{
			filterContext.HttpContext.Response.Redirect("/test/Home");
		}
		public bool getTokenIsOk(string Token, string ClientToken, HttpContextBase httpContext)
		{
			bool SessionIsOk = false;
			if (Token == ClientToken)
			{
				SessionIsOk = true;
			}
			else
			{
				TypeDesToken typeDesToken = new TypeDesToken();
				//解析一下传入的token,如果可以重新进行session的赋值
				string jiemi = typeDesToken.FoXiGetToken(ClientToken);
				string[] uNameAndPwd = jiemi.Split('|');
				if (uNameAndPwd != null && uNameAndPwd.Length == 2)
				{
					string buffUname = uNameAndPwd[0];
					string buffUpwd = uNameAndPwd[1];
					var getLoginModel = userInfosService.LoadEntities(x => x.Uname == buffUname && x.Upwd == buffUpwd).FirstOrDefault();
					if (getLoginModel != null)
					{
						Token = typeDesToken.FoXiMakeToken(getLoginModel.Uname, getLoginModel.Upwd);
						httpContext.Session["Token"] = new ServiceUserToken() { uid = getLoginModel.Id, Token = Token };
						SessionIsOk = true;
					}
				}
			}
			return SessionIsOk;
		}

	}
}